<?php
namespace App\Helpers;

include base_path('aliyun-oss-php-sdk/autoload.php');

use Push\Request\V20160801 as Push;

/**
 * Class Push
 * @package App\Helpers
 *
 * https://help.aliyun.com/knowledge_detail/48089.html
 *  这里是移动推送。目前接入的方式是阿里云。
 * 使用方式 请参考 job 下面的 MobilePushJob
 */
class AliyunOss
{
    /**
     * 将消息推送到客户端。
     * @param array $data 推送的数据信息;
     * @return bool;
     */
    public static function pushInfo($data)
    {
        if(empty($data) || !is_array($data))
        {
            return false;
        }
        if(!isset($data['userId']) || empty($data['userId'])) {
            return false;
        }
        if(!isset($data['clientType']) || empty($data['clientType']) || !in_array($data['clientType'],['ios','android']))
        {
            return false;
        }
        if(!isset($data['title']) || empty($data['title'])) {
            return false;
        }
        if(!isset($data['body']) || empty($data['body']))
        {
            return false;
        }
        $noticBody = $data['body'];
        // 如果有扩展字段
        if(isset($data['extParameters']) && !empty($data['extParameters']) && is_array($data['extParameters']))
        {
            $data['body'] = $data['extParameters'] = json_encode($data['extParameters'],JSON_UNESCAPED_UNICODE);
            $data['boby'] = $noticBody;
        }
        else
        {
            unset($data['extParameters']);
        }
        $aliyunPushConfig = config('app.aliyunPush');
        $accessKeyId = $aliyunPushConfig['accessKeyId'];
        $accessKeySecret = $aliyunPushConfig['accessKeySecret'];
        $appKey = $aliyunPushConfig[$data['clientType']]['appKey'];
        $appSecret = $aliyunPushConfig[$data['clientType']]['appSecret'];
        if(empty($appKey))
        {
            return false;
        }
        $target  = (isset($data['target']) && !empty($data['target']))?$data['target']:'ACCOUNT';

        //构建连接
        $iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", $accessKeyId, $accessKeySecret);
        $client = new \DefaultAcsClient($iClientProfile);
        $request = new Push\PushRequest();
        $request->setAcceptFormat('JSON');
        // 推送目标
        $request->setAppKey($appKey);

        $request->setTarget($target); //推送目标: DEVICE:推送给设备; ACCOUNT:推送给指定帐号,TAG:推送给自定义标签; ALL: 推送给全部
        $request->setTargetValue($data['userId']); //根据Target来设定，如Target=device, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        $request->setPushType("MESSAGE"); //消息类型 MESSAGE NOTICE
        $request->setTitle($data['title']); // 消息的标题
        $request->setBody($data['body']); // 消息的内容
        //设置ios的推送信息
        if('ios' == $data['clientType'])
        {
            $request->setDeviceType('iOS'); //设备类型 ANDROID iOS ALL.
            //设置音乐
            $request->setiosMusic(isset($data['Music'])?$data['Music']:"default");
            $request->setiOSBadgeAutoIncrement(true);
            // iOS通知副标题内容（iOS 10+）
            if(isset($data['subtitle']) && !empty($data['subtitle']))
            {
                $request->setiOSSubtitle($data['subtitle']);
            }
            //指定iOS通知Category（iOS 10+）
            if(isset($data['notificationCategory']) && !empty($data['notificationCategory']))
            {
                $request->setiOSNotificationCategory($data['notificationCategory']);
            }
            //通知扩展
            if(isset($data['extParameters']) && !empty($data['extParameters']))
            {
                $request->setiOSMutableContent(true);
                //iOS通知的扩展属性,iOS 10+ 可以在此指定富媒体推送通知的资源Url: {“attachment”: “https://xxxx.xxx/notification_pic.png"} (注意 : 该参数要以json map的格式传入,否则会解析出错)
                $request->setiOSExtParameters($data['extParameters']);
            }
            //设置推送环境
            $request->setiOSApnsEnv(config('app.pushEnv','PRODUCT'));
            //消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
            $request->setiOSRemind(true);
            $request->setiOSRemindBody($noticBody);
        }
        //安卓设备的配置信息
        if('android' == $data['clientType'])
        {
            $request->setDeviceType('ANDROID'); //设备类型 ANDROID iOS ALL.
            //通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
            $request->setAndroidNotifyType(isset($data['notifyType'])?$data['notifyType']:"BOTH");
            //打开类型。 点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
            $request->setAndroidOpenType('ACTIVITY');
            //设定通知打开的activity，仅当AndroidOpenType="Activity"有效
            $request->setAndroidActivity('com.alibaba.cloudpushdemo.bizactivity');
            //Android通知音乐
            $request->setAndroidMusic(isset($data['Music'])?$data['Music']:"default");
            //通知栏自定义样式0-100
            $request->setAndroidNotificationBarType(isset($data['notificationBarType'])?intval($data['notificationBarType']):1);
            //Android通知在通知栏展示时排列位置的优先级 -2 -1 0 1 2
            if(isset($data['notificationBarPriority']))
            {
                $request->setAndroidNotificationBarPriority($data['notificationBarPriority']);
            }
            //设置NotificationChannel参数，具体用途请参考常见问题：Android 8.0以上设备通知接收不到
            //https://help.aliyun.com/knowledge_detail/67398.html
            if(isset($data['notificationChannel']))
            {
                $request->setAndroidNotificationChannel($data['notificationChannel']);
            }
            //设定通知的扩展属性。(注意 : 该参数要以 json map 的格式传入,否则会解析出错)
            if(isset($data['extParameters']) && !empty($data['extParameters']))
            {
                $request->setAndroidExtParameters($data['extParameters']);
            }
            if(isset($data['clientChannel']) && !empty($data['clientChannel']))
            {
                if(in_array(strtolower($data['clientChannel']),['xiaomi','huawei','fcm']))
                {
                    $request->setAndroidRemind(true);
                    // 此处需改动
                    $request->setAndroidPopupActivity('com.alibaba.cloudpushdemo.bizactivity');
                    $request->setAndroidPopupTitle($data['title']);
                    $request->setAndroidPopupBody($data['body']);
                }
            }
        }
        /*********推送控制****************/
        if(isset($data['pushTime']) && date("Y-m-d H:i:s",strtotime($data['pushTime'])) == $data['pushTime'])
        {
            $request->setPushTime($data['pushTime']);
        }
        //离线消息
        $request->setStoreOffline(true);
        //离线消息/通知的过期时间，和StoreOffline配合使用，过期则不会再被发送，最长保存72小时。默认为72小时。时间格式按照ISO8601标准表示，并需要使用UTC时间，格式为YYYY-MM-DDThh:mm:ssZ，过期时间不能小于当前时间或者定时发送时间加上3秒（ExpireTime > PushTime + 3秒），3秒是为了冗余网络和系统延迟造成的误差。
        if(isset($data['pushExporeTime']) && date("Y-m-d H:i:s",strtotime($data['pushExporeTime'])) == $data['pushExporeTime'])
        {
            $request->setExpireTime($data['pushExporeTime']);
        }
        try
        {
            $response = $client->getAcsResponse($request);
            $response = Comm::stdClassToArray($response);
            $response['userId']= $data['userId'];
            if(isset($response['Code']))
            {
                $response['error']="pushError";
                $response['data'] = $data;
            }
            Log::info('aliyunpush response',[$response],'aliyunpush/push');
            return true;
        }
        catch(\Exception $e)
        {

            $response['userId']= $data['userId'];
            $response['status']= 'error';
            $response['data'] = $data;
            Log::info('aliyunpush response',[$response],'aliyunpush/push');
            return true;
        }
    }
}